/****************************************************************************
**
** Packet.cpp
**
** Copyright (C) August 2014 Hotride
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
*****************************************************************************
*/
//---------------------------------------------------------------------------
#include "stdafx.h"
//---------------------------------------------------------------------------
TMessageFragment::TMessageFragment(PBYTE buf, int size, int msg_size)
: m_size(size), m_msg_size(msg_size)
{
	if (m_msg_size == 0) m_data = new BYTE[3];
	else m_data = new BYTE[msg_size];

	memcpy(m_data, buf, m_size);
}
//---------------------------------------------------------------------------
int TMessageFragment::Append(PBYTE buf, int size)
{
	if (m_msg_size == 0)
	{
		if(m_size + size < 3)
		{
			memcpy(m_data + m_size, buf, size);
			m_size += size;

			return size;
		}

		if (m_size == 2) m_msg_size = (m_data[1] << 8) | buf[0];
		else  m_msg_size = (buf[0] << 8) | buf[1];

		PBYTE newbuf = new BYTE[m_msg_size];
		memcpy(newbuf, m_data, m_size);

		delete m_data;

		m_data = newbuf;
	}

	int append_size = m_msg_size - m_size;

	if (append_size > size) append_size = size;

	// Concatenate the new data onto the fragment
	memcpy(m_data + m_size, buf, append_size);
	m_size += append_size;

	return append_size;
}
//---------------------------------------------------------------------------